package com.zy.web.servlet;

import com.zy.pojo.ResultInfo;
import com.zy.web.servlet.base.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-06-09
 * Time: 下午 19:55
 * Description: 文件上传
 */
@WebServlet("/file/*")
public class FileUploadServlet extends BaseServlet {

    public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建DiskFileItemFactory工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //创建servletFileUpload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        ResultInfo resultInfo = new ResultInfo();

        //设置字符编码
        fileUpload.setHeaderEncoding("utf-8");
        //解析request，得到的上传文件的FileItem对象
        List<FileItem> fileItems = null;
        try {
            fileItems = fileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        for (FileItem item : fileItems) {
            // 上传项
            InputStream is = item.getInputStream();
            String realPath = getServletContext().getRealPath("/static/image/");
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //获取文件名
            String filename = item.getName();
            if (!"".equals(filename) && filename != null) {
                filename = UUID.randomUUID().toString() + filename;
                file = new File(file, filename);
                file.createNewFile();
                resultInfo.setCode(200);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("url", "http://localhost:8080" + request.getContextPath() + "/static/image/" + filename);
                map.put("filename", filename);
                resultInfo.setData(map);
                resultInfo.setMessage("上传成功");
                //这里直接借助commons.io来做io对接，不然需要做流的读取和写入
                FileOutputStream fos = new FileOutputStream(file);//把输入流的数据拷贝到输出流
                IOUtils.copy(is, fos);
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }
        }
        writeValue(resultInfo, response);
    }

}